package com.forum.framework.security.core.rpc;

import com.forum.framework.common.util.json.JsonUtils;
import com.forum.framework.security.core.LoginUser;
import com.forum.framework.security.core.util.SecurityUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 功能:LoginUser 的 RequestInterceptor 实现类：Feign 请求时，将 {@link com.forum.framework.security.core.LoginUser} 设置到 header 中，继续透传给被调用的服务
 * 作者:ouyzh
 * 日期:2025/3/1 20:13
 */
public class LoginUserRequestInterceptor implements RequestInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginUserRequestInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            return;
        }
        try {
            String userStr = JsonUtils.toJsonString(loginUser);
            userStr = URLEncoder.encode(userStr, StandardCharsets.UTF_8); // 编码，避免中文乱码
            requestTemplate.header(SecurityUtils.LOGIN_USER_HEADER, userStr);
        } catch (Exception ex) {
            log.error("[apply][序列化 LoginUser({}) 发生异常]", loginUser, ex);
            throw ex;
        }
    }
}
